package com.jindi.jacococli.biz.business.client;

import com.jindi.jacococli.biz.config.AppProperties;
import com.jindi.jacococli.biz.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.gitlab4j.api.models.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;

import static com.jindi.jacococli.biz.constant.Constant.*;

@Slf4j
@Service
public class GitClientImpl implements GitClient {
    public static final Logger LOGGER = LoggerFactory.getLogger(GitClientImpl.class);

    @Resource
    private AppProperties appProperties;

    @Override
    public boolean clone(String branchName, Project project, File execDir, String service) {
        String httpUrlToRepo = project.getHttpUrlToRepo();
        if (httpUrlToRepo.startsWith(PROTOCOL_HTTPS)) {
            httpUrlToRepo = PROTOCOL_HTTPS + OAUTH2 + appProperties.getAccessToken() + "@" + httpUrlToRepo.substring(PROTOCOL_HTTPS.length());
        } else if (httpUrlToRepo.startsWith(PROTOCOL_HTTP)) {
            httpUrlToRepo = PROTOCOL_HTTP + OAUTH2 +  appProperties.getAccessToken() + "@" + httpUrlToRepo.substring(PROTOCOL_HTTP.length());
        }

        File exist = new File(service);
        String command;
        if (exist.exists()) {
            command = String.format(GIT_PULL_BRANCH, branchName, httpUrlToRepo);
        } else {
            command = String.format(GIT_CLONE_BRANCH, branchName, httpUrlToRepo);
        }
        LOGGER.info("clone command:{}", command);
        return ProcessUtils.execCommand(command, execDir);
    }
}
